<%@ page import="com.sap.mw.jco.IFunctionTemplate" %>
<%@ page import="com.sap.mw.jco.JCO" %>
<%@ page import="com.weaver.general.BaseBean" %>
<%@ page import="com.weaver.integration.datesource.SAPInterationOutUtil" %>
<%@ page import="com.weaver.integration.log.LogInfo" %>
<%@ page import="org.dom4j.Document" %>
<%@ page import="org.dom4j.DocumentHelper" %>
<%@ page import="org.dom4j.Node" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="java.io.BufferedReader" %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="java.io.OutputStream" %>

<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>

<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<jsp:useBean id="rs1" class="weaver.conn.RecordSet"/>
<%
    String sapcode = Util.null2String(request.getParameter("sapcode"));//SAP Code
    String po = Util.null2String(request.getParameter("po"));//PO
    Map<String,String> resultMap =getXMLData(po,sapcode);
    String RetFlag = Util.null2String(resultMap.get("RetFlag"));
    String MSG = Util.null2String(resultMap.get("MSG"));
    if(resultMap.size()>0 && RetFlag.equals(false)){
      if(!"".equals(MSG)){
          String  message = "提示异常信息: BPM Exception："+ MSG;
          String json ="{\"flag\":\"0\",\"message\":\"" + message + "\"}";
          out.print(json);
      }
    }else {
         Map<String,String> returnMap = execute(po,sapcode);
        String e_land1 = Util.null2String(returnMap.get("e_land1"));//国内外- 从SAP中传CN过来,是国内,非CN的,为国外
        String e_menge = Util.null2String(returnMap.get("e_menge"));//PO数量
        String e_netpr = Util.null2String(returnMap.get("e_netpr"));//单价
        String e_waers = Util.null2String(returnMap.get("e_waers"));//币种
        String json ="{\"flag\":\"1\",\"e_land1\":\"" + e_land1 + "\",\"e_menge\":\"" + e_menge
                + "\",\"e_netpr\":\"" + e_netpr + "\",\"e_waers\":\"" + e_waers + "\"}";
        out.print(json);
    }
%>
<%!
    public Map execute(String pono, String sapcode) {
        SAPInterationOutUtil outUtil = new SAPInterationOutUtil();
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("in---ZBPM_PO_LIST");
        JCO.Client myConnection = (JCO.Client) outUtil.getConnection("2", new LogInfo());
        myConnection.connect();
        JCO.Repository myRepository = new JCO.Repository("Repository", myConnection); // 只一个名字
        IFunctionTemplate ft = myRepository.getFunctionTemplate("ZBPM_PO_LIST");//设置BAPI函数
        JCO.Function bapi = ft.getFunction();
        JCO.ParameterList input = bapi.getImportParameterList();//输入参数和结构处理
        JCO.ParameterList inputtable = bapi.getTableParameterList();//输入表的处理
        //输入参数
        input.setValue(pono, "I_EBELN");
        input.setValue(sapcode, "I_MATNR");

        //执行函数
        myConnection.execute(bapi);
        JCO.ParameterList out = bapi.getExportParameterList();//输出参数和结构处理
        JCO.ParameterList Table00 = bapi.getTableParameterList();//输出表的处理

        //返回处理结果以及日志
        Map<String,String> resultMap = new HashMap<>();
        String e_land1 = Util.null2String(out.getValue("E_LAND1"));
        String e_menge = Util.null2String(out.getValue("E_MENGE"));
        String e_netpr = Util.null2String(out.getValue("E_NETPR"));
        String e_waers = Util.null2String(out.getValue("E_WAERS"));
        resultMap.put("e_land1",e_land1);
        resultMap.put("e_menge",e_menge);
        resultMap.put("e_netpr",e_netpr);
        resultMap.put("e_waers",e_waers);
        baseBean.writeLog("SPA_COUNTS:" + resultMap.toString());
        //返回处理结果以及日志
        JCO.releaseClient(myConnection);
        return resultMap;
    }

    public static Map<String,String>  getXMLData(String pono,String sapcode) {//4100000021,QCAF0001
        Map<String,String> returnMap = new HashMap<>();
        String json = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <tem:CheckPOForBPM>\n" +
                "         <!--Optional:-->\n" +
                "         <tem:PONO>"+pono+"</tem:PONO>\n" +
                "         <!--Optional:-->\n" +
                "         <tem:SapCode>"+sapcode+"</tem:SapCode>\n" +
                "      </tem:CheckPOForBPM>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        try {
            StringBuffer result = toWebService(json,"http://172.27.108.41:8081/webservice/material.asmx?op=CheckPOForBPM" );
            Document document= DocumentHelper.parseText(result.toString());//xmlStr为上图格式的字符串
            Node RetFlag=document.selectSingleNode("//RetFlag");//获取节点对象,注意引号内的“//”必须加 ，否则报错
            Node MSG=document.selectSingleNode("//MSG");
            //根据节点对象获取相应信息
            String RetFlagValue=RetFlag.getText();
            String MSGValue=MSG.getText();
            returnMap.put("RetFlag",RetFlagValue);
            returnMap.put("MSG",MSGValue);
            System.out.println(returnMap.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnMap;
    }

    // 调用WS
    public static StringBuffer toWebService(String sendMsg,String INVOICE_WS_URL) throws Exception {
        //拼接请求报文

        // 开启HTTP连接ַ
        InputStreamReader isr = null;
        BufferedReader inReader = null;
        StringBuffer result = null;
        OutputStream outObject = null;
        try {
            URL url = new URL(INVOICE_WS_URL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            // 设置HTTP请求相关信息
            httpConn.setRequestProperty("Content-Length",
                    String.valueOf(sendMsg.getBytes().length));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);

            // 进行HTTP请求
            outObject = httpConn.getOutputStream();
            outObject.write(sendMsg.getBytes());

            if (200 != (httpConn.getResponseCode())) {
                throw new Exception("HTTP Request is not success, Response code is " + httpConn.getResponseCode());
            }
            // 获取HTTP响应数据
            isr = new InputStreamReader(
                    httpConn.getInputStream(), "utf-8");
            inReader = new BufferedReader(isr);
            result = new StringBuffer();
            String inputLine;
            while ((inputLine = inReader.readLine()) != null) {
                result.append(inputLine);
            }
            return result;

        } catch (IOException e) {
            new BaseBean().writeLog("e::"+e);
            throw e;
        } finally {
            // 关闭输入流
            if (inReader != null) {
                inReader.close();
            }
            if (isr != null) {
                isr.close();
            }
            // 关闭输出流
            if (outObject != null) {
                outObject.close();
            }
        }

    }
%>
